"use strict";

const crypto = require("crypto");
const moment = require("moment");

var urlencode = require("urlencode");

const CryptoJS = require("crypto-js");

/**
 * sha156 签名算法
 * @param {String} str - 需要签名的字符串
 * @param {String} saltKey - secert
 */
const sha256 = (str, saltKey) => {
  let hash = crypto
    .createHmac("sha256", saltKey)
    .update(str + "\n" + saltKey, "utf8")
    .digest("base64");
  console.log(hash);
  const signature = encodeURIComponent(hash);
  console.log(signature);
  return signature;
};

const _sha256 = saltKey => {
  const timestamp = Date.now();
  const stringToSign = `${timestamp}\n${saltKey}`;

  const hash = crypto
    .createHmac("sha256", saltKey)
    .update(stringToSign, "utf-8")
    .digest("base64");

  const sign = encodeURI(hash);
  return {
    timestamp,
    sign
  };
};

// sha256('1546084445901','testappSecret');

// const timestamp=moment(new Date()).valueOf()+'';
// const accessKey='dingoarhla5gdknnn6fll2'; //appid

// const timestamp = "1546084445901";
// const accessKey = "testappSecret"; //appid
// // const signature = sha256(timestamp, accessKey);
// const signature = _sha256(timestamp, accessKey);
// console.log(
//   `curl 'https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=${signature}&timestamp=${timestamp}&accessKey=${accessKey}' -H "Content-Type:application/json" -X POST --data '{"tmp_auth_code":"tmp_auth_code"}'`
// );

const signature = saltKey => {
  const timestamp = Date.now();
  //   const stringToSign = `${timestamp}\n${saltKey}`;
  var signature = CryptoJS.HmacSHA256(timestamp, saltKey);
  signature = CryptoJS.enc.Base64.stringify(signature);
  signature = urlencode.encode(signature, "utf-8");
  console.log(signature);
  return {
    timestamp: timestamp,
    sign: signature
  };
};

// signature();

module.exports = {
  sha256: sha256,
  _sha256: _sha256,
  signature: signature
};
